function open_create_creditmemo(){
	u_hideAllSections();
	u_safeShowElement('createcreditmemo_table_container');
	init_cmocreate();
	getClientsList(usr_comp_cache.companyId);
	if(!isNavigationFromBackButton){
	var functionPointerObj = new Object();
	functionPointerObj.functionName = "open_create_creditmemo()";
	navigationStateArray.push(functionPointerObj);
	}
}
var cmo_date_cal = null;
function init_cmocreate(){
	cmo_createyuitable();
	clear_cmemolitem_yui_table() ;
	dwr.util.removeAllOptions("cmo_client");
	dwr.util.removeAllOptions("cmo_invnum");

	dwr.util.setValue('cmo_supplier', usrcompany_name);
	dwr.util.setValue('cmo_date', format_date(new Date()));
	dwr.util.setValue('cmo_cf1',"");
	dwr.util.setValue('cmo_cf2',"");
	dwr.util.setValue('cmo_cf3',"");
	
	dwr.util.setValue('cmo_num',"");
	dwr.util.setValue('cmo_totalamt',0);
	assignAttachmentComponent("attachmentComponetPlaceHolder5");
	assignCommentsComponent("commentComponetPlaceHolder5");
	
	if(cmo_date_cal == null){
		cmo_date_cal = new JsDatePick({
			useMode:2,
			target:"cmo_date",
			dateFormat:"%m/%d/%Y",
			limitToToday:true,
			cellColorScheme:"aqua",
			dateFormat:"%m/%d/%Y",
			imgPath:"/thirdpartyscripts/jsdatepick/img/",
			weekStartDay:1
		});
	}
}


function cmo_selClient(){
	var clientid = dwr.util.getValue('cmo_client');
	dwr.util.removeAllOptions("cmo_invnum");
	var cliinv = new Array();
	cliinv.push({invoiceNumber: "   "});
	if(!isEmptyString(clientid)){
		if(invsent_cache != null){
			for(var i=0;i<invsent_cache.length;i++){
				if(invsent_cache[i].invoicedToCompany == clientid){
					cliinv.push(invsent_cache[i]);
				}
			}
			
			dwr.util.addOptions("cmo_invnum", cliinv, "invoiceNumber", "invoiceNumber");
		}
	}
	clear_cmemolitem_yui_table();
}

function cmo_selInvoice(){
	var invid = dwr.util.getValue('cmo_invnum');
	cmo_loadInvDetails(invid);
	
}

var selinvoice = null;
function cmo_loadInvDetails(invid){
	selinvoice = null;
	if(invsent_cache != null){
		for(var i=0;i<invsent_cache.length;i++){
			if(invsent_cache[i].invoiceNumber == invid){
				selinvoice = invsent_cache[i];
				break;
			}
		}
	}
	
	if(selinvoice == null){
		return;
	}
	
	cmo_populateLineItems();
	
}

YAHOO.widget.DataTable.textcmla = function(elLiner, oRecord, oColumn, oData) {
	if(isEmptyString(oData)){
		elLiner.innerHTML = "<input type='text' value='"+oRecord.getData('lineAmount')+"' id='"+oRecord.getId() + "-input-cmoamout' onblur='update_cmolineamt(this);'>"  ;
	}else{
		elLiner.innerHTML = "<input type='text' value='"+oData+"' id='"+oRecord.getId() + "-input-cmoamout' onblur='update_cmolineamt(this);'>" ;
	}
};


var cmo_lineItemReadOnlycolumnDefs = [ {
	key : "invoiceLineNumber",
	label : "Line #",
	width : "50px"
	
}, {
	key : "select",
	label : "Select",
	width : "50px",
	formatter: "checkbox"
	
},{
	key : "partNumber",
	label : "Part Number",
	width : "50px"
	
},{
	key : "invoiceLineDescription",
	label : "Description",
	width : "50px"
}, {
	key : "quantity",
	label : "Quantity",
	width : "50px"
	
} ,{
	key : "uomSymbol",
	label : "Unit Of Measure",
	width : "50px"
} ,{
	key : "unitPrice",
	label : "Unit Price",
	width : "50px"
} ,{
	key : "lineAmount",
	label : "Invoice Line Amount",
	width : "50px",
	formatter: YAHOO.widget.DataTable.textcmla
} ,{
	key : "unitCurrencySymbol",
	label : "Currency",
	width : "50px"
},{
	key : "lineAmount",
	label : "Total",
	width : "50px"
} , ];


var cmo_lineyuitable = null;
function cmo_populateLineItems(){
	cmo_createyuitable();
	clear_cmemolitem_yui_table() ;
	if(selinvoice != null && selinvoice.invoiceLineItems != null){
		cmo_lineyuitable.addRows(selinvoice.invoiceLineItems);
	}
}

function cmo_createyuitable(){
	if(cmo_lineyuitable == null){
	var invlDataSource = new YAHOO.util.DataSource();
	invlDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
	cmo_lineyuitable = new YAHOO.widget.DataTable("cmo_lineDetails_yuiTable",cmo_lineItemReadOnlycolumnDefs,invlDataSource,{});
	
	cmo_lineyuitable.unsubscribeAll("checkboxClickEvent");
	cmo_lineyuitable.subscribe("checkboxClickEvent", function(oArgs){   
    	var elCheckbox = oArgs.target;
		var newValue = elCheckbox.checked;
		var record = this.getRecord(elCheckbox);
		var column = this.getColumn(elCheckbox);
		record.setData(column.key,newValue);
			//Total Credit Memo Amount:
			var total = 0;
			var rst = cmo_lineyuitable.getRecordSet();
			for(var k=0;k<rst.getLength();k++){
				var data = rst.getRecord(k);
				if(data.getData('select')){
					total = total + Number(dwr.util.getValue(data.getId() + '-input-cmoamout'));
				}
			}
			
			dwr.util.setValue('cmo_totalamt',total);
     }); 
	}
}

function update_cmolineamt(inputid){
	var val = inputid.value;
	if(isNaN(Number(val)) || Number(val) < 0){
		alert('Please enter a non-zero number.');
		inputid.value = '0';
		return;
	}
	
	
	var rec = cmo_lineyuitable.getRecord(inputid.id.replace('-input-cmoamout',''));
	if(rec && rec != null){
		var poamt = rec.getData('lineAmount');
		if(Number(poamt) < Number(val)){
			alert('Credit Memo Line amount must be less than or equal to the Invoice Line amount.');
			return;
		}else{
			cmo_lineyuitable.updateCell(rec, cmo_lineyuitable.getColumn('lineAmount'),val, true);
			//inv_lineyuitable.updateCell(rec, inv_lineyuitable.getColumn('lineAmount'),val, false);
			
			//Total Credit Memo Amount:
			var total = 0;
			var rst = cmo_lineyuitable.getRecordSet();
			for(var k=0;k<rst.getLength();k++){
				var data = rst.getRecord(k);
				if(data.getData('select')){
					total = total + Number(data.getData('lineAmount'));
				}
			}
			
			dwr.util.setValue('cmo_totalamt',total);
		}
	}
}


function createcreditmemo(){
	var inv = {};
	var invli = new Array();
	
	//browse through the yui table.
	var rset = cmo_lineyuitable.getRecordSet();
	for(var i=0;i<rset.getLength();i++){
		var rec = rset.getRecord(i);
		if(rec.getData('select')){
			var invlineitem = rec._oData;
			var item = {};
			item.creditMemoNumber = dwr.util.getValue('cmo_num');
			item.creditMemoLineNumber = invlineitem.invoiceLineNumber;
			item.partNumber = invlineitem.partNumber;
			item.quantity = invlineitem.quantity;
			item.unitPrice = invlineitem.unitPrice;
			item.unitCurrency = invlineitem.unitCurrency;
			item.unitOfMeasure = invlineitem.unitOfMeasure;
			item.lineAmount = invlineitem.lineAmount;
			
			invli.push(item);
		}
	}
	
	inv.creditMemoLines = invli;	
	inv.supplierInvoiceNumber = dwr.util.getValue('inv_num');
	inv.invoiceNumber = dwr.util.getValue('cmo_invnum');
	inv.creditMemoDescription = dwr.util.getValue('cmo_title');
	inv.mainSupplierCompany = usr_comp_cache.companyId;
	inv.remitToSupplierCompany = usr_comp_cache.companyId;
	inv.creditMemoDate = new Date();
	inv.creditMemoCreateDate = new Date();
	inv.creditMemoSubmittedDate = new Date();
	inv.creditMemoComposer = usrname;
	inv.creditMemoOwner = usrname;
	inv.totalCreditMemoAmount = Number(dwr.util.getValue('cmo_totalamt'));
	inv.originatingSystem = 'ATSCOII';
	inv.originatingCompany = usr_comp_cache.companyId;
	inv.customField1 = dwr.util.getValue('cmo_cf1');
	inv.customField2 = dwr.util.getValue('cmo_cf2');
	inv.customField3 = dwr.util.getValue('cmo_cf3');
	inv.creditMemoToCompanyName = $('cmo_client').options[$('cmo_client').selectedIndex].text;
	inv.creditMemoFromCompanyName = usr_comp_cache.companyName;
	inv.creditMemoToCompany = dwr.util.getValue('cmo_client');
	
	try{
		var poAtchArr = new Array();
		if(attachmentctr > 0){
			for(var ip=0;ip<attachmentctr;ip++){
				if($('poattachments_check'+ip+'').checked){
					poAtchArr.push(dwr.util.getValue('poaattach_id'+ip+''));
				}
			}
		}
		
		if(poAtchArr.length > 0){
			inv.creditmemoAttachmentIds = poAtchArr;
		}
		
		
		var pocmtarr = new Array();
		if(pocomments_ctr > 0){
			for(var iq=0;iq<pocomments_ctr;iq++){
				if($('pocomment_check'+iq+'').checked){
					pocmtarr.push(dwr.util.getValue('pocomment_text'+iq+''));
				}
			}
		}
		
		if(pocmtarr.length > 0){
			inv.creditMemoComments = pocmtarr;
		}
	}catch(ex){
		
	}
	//validate
	
	//Submit the invoice.
	var dwrCallMetaData = {
			callback : success_subcreditmemo,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler
		};

	DWR_Invoice.submitCreditMemo(inv, dwrCallMetaData);
}

function success_subcreditmemo(dwrresp){
	if (dwrresp && dwrresp.respCode == 0) {
		alert("Credit Memo Created Successfully.");
		return;
	}

	alert("Credit Memo could not be created. Please try again.");
}

function clear_cmemolitem_yui_table() {
	if (cmo_lineyuitable != null && cmo_lineyuitable.getRecordSet() != null && cmo_lineyuitable.getRecordSet().getLength() > 0) {
		var length = cmo_lineyuitable.getRecordSet().getLength();
		if (length > 0) {
			cmo_lineyuitable.deleteRows(0, length);
		}
	}
}